package com.parktech.sun.web.controller.management.downloadcenter;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.downloadcenter.ResourceFile;
import com.parktech.sun.domain.model.downloadcenter.ResourceType;
import com.parktech.sun.domain.model.industryinfo.IndustryInfoCategory;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.downloadcenter.ResourceFileService;
import com.parktech.sun.utils.FileHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: Think
 * Date: 11-1-23
 * Time: 下午11:52
 */
@Controller
@RequestMapping("/management/resourcefiles")
public class ResourceFileController {
    
    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private ResourceFileService resourceFileService;

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Autowired
    public ResourceFileController(ResourceFileService resourceFileService) {
        this.resourceFileService = resourceFileService;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView search(@ModelAttribute ResourceFileSearchForm resourceFileSearchForm) {

        Page page = new Page(pageSize, resourceFileSearchForm.getPageNo());

        ModelAndView modelAndView = new ModelAndView("management/resourcefile/resourceFileSearch");

        return modelAndView.addObject(
                resourceFileService.search(
                        resourceFileSearchForm.getName(), resourceFileSearchForm.getPublishStatus(), page));
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("resourceFileIds") Long[] resourceFileIds) {
        resourceFileService.deleteAll(resourceFileIds);
        return "redirect:search";
    }

    @ModelAttribute("resourceFile")
    public ResourceFile populateModel(HttpServletRequest request) {
        String strId = request.getParameter("id");

        if (strId == null || strId.equals("-1")) {
            return new ResourceFile();
        }
        return resourceFileService.getById(new Long(strId));
    }

    @RequestMapping(value = "/{resourceFileId}", method = RequestMethod.GET)
    public String edit(@PathVariable Long resourceFileId, Model model) {
        ResourceFile resourceFile = resourceFileService.getById(resourceFileId);
        model.addAttribute(resourceFile);
        return "management/resourcefile/resourceFileForm";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute(new ResourceFile());
        return "management/resourcefile/resourceFileForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid ResourceFile resourceFile,
                       @RequestParam("resourceFile") MultipartFile uploadResourceFile,
                       HttpServletRequest request)
            throws IOException {

        resourceFileService.saveOrUpdateBean(resourceFile);

        if (uploadResourceFile != null && !uploadResourceFile.isEmpty()) {
            processFile(resourceFile, uploadResourceFile, request.getSession().getServletContext());
        }
        
        resourceFileService.saveOrUpdateBean(resourceFile);

        return "redirect:/management/resourcefiles/search";
    }

    @ModelAttribute("allCategories")
    public List<ResourceType> populateAllCategories() {
        return resourceFileService.searchType(null, new Page(1000, 1)).getResult();
    }

    @ModelAttribute("allPublishStatus")
    public Map<Integer, String> populateAllPublishStatus() {
        Map<Integer, String> allPublishStatus = new HashMap<Integer, String>();
        allPublishStatus.put(0, "未发布");
        allPublishStatus.put(1, "已发布");
        return allPublishStatus;
    }

    private void processFile(ResourceFile resourceFile, MultipartFile uploadResource, ServletContext servletContext) throws IOException {

        String resourceFilePath = servletContext.getRealPath("/upload/resourceFile/" + resourceFile.getId());
        File resourceFileDir = new File(resourceFilePath);
        if (!resourceFileDir.exists()) resourceFileDir.mkdirs();

        File uploadResourceFile = new File(resourceFileDir, uploadResource.getOriginalFilename());
        if (uploadResourceFile.exists()) {
            uploadResourceFile.delete();
        }
//        ImageHelper.resizeFix(uploadResource.getInputStream(), uploadResourceFile, 150, 75);
        FileHelper.saveFile(uploadResource.getInputStream(), uploadResourceFile);
        resourceFile.setFileName(uploadResource.getOriginalFilename());
        resourceFile.setFileSize(getSize(uploadResource.getSize()) + "MB");
    }

    private String getSize(long size) {
        BigDecimal bigDecimal = new BigDecimal(size);
        return bigDecimal.divide(new BigDecimal(1024*1024), 2, RoundingMode.UP).toString();
    }

}
